<template>
  <div class="traceability-container">
    <div class="btn-group">
      <el-button type="primary" @click="handleAdd" round>
        <el-icon style="vertical-align: middle;">
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-button type="danger" @click="handleDelete" round>删除</el-button>
    </div>
    <div class="table-scroll-wrapper">
      <el-table :data="tableData" border class="beauty-table" style="min-width: 1200px; margin-top: 20px"
        max-height="500px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="GoodName" label="商品名称" width="140" align="center" />
        <el-table-column prop="Batch" label="生产批次" width="100" align="center" />
        <el-table-column prop="QGPeriod" label="保质期(天)" width="100" align="center" />
        <el-table-column prop="PLNumber" label="生产许可证号" width="150" align="center" />
        <el-table-column prop="Manufacturer" label="生产企业" width="200" align="center" />
        <el-table-column prop="Information" label="信息完整度" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.Information === '100%' ? 'success' : (scope.row.infoPercent === '80%' ? 'warning' : 'danger')"
              effect="plain">
              {{ scope.row.Information }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="CreateName" label="创建人" width="100" align="center" />
        <el-table-column prop="CreateDate" label="创建时间" width="180" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.CreateDate">{{ moment(scope.row.CreateDate).format("YYYY-MM-DD") }}</span>
            <span v-else>---</span>
          </template>
          </el-table-column>
        <el-table-column prop="UpdateName" label="修改人" width="100" align="center" />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <el-link type="primary" @click="handleDetail(scope.row.Batch)" class="action-link">详情</el-link>
            <el-link type="warning" @click="handleEdit(scope.row)" class="action-link">修改</el-link>
            <el-link type="success" @click="handleExport(scope.row)" class="action-link">导出溯源码</el-link>
            <el-link type="danger" @click="handleDeleteRow(scope.row.Id)" class="action-link">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer-bar">
      <el-pagination background :total="Total.TotalCount" :current-page="Total.PageIndex" :page-size="Total.PageSize"
        :page-sizes="[15, 30, 50, 100]" layout="sizes, ->, total, prev, pager, next"
        @size-change="(size) => { Total.PageSize = size; Total.PageIndex = 1; ShowBasic(); }"
        @current-change="(page) => { Total.PageIndex = page; ShowBasic(); }" class="beauty-pagination">
        <template #sizes>
          <span style="margin-right: 8px;">每页显示</span>
          <div class="page-size-group">
            <el-button v-for="size in [10, 15, 30, 50, 100]" :key="size" size="small"
              :type="Total.PageSize === size ? 'primary' : 'default'" @click="changePageSize(size)"
              style="margin-right: 4px;">
              {{ size }}
            </el-button>
          </div>
          <span style="margin-left: 8px;">条</span>
        </template>
      </el-pagination>
    </div>
    <el-dialog v-model="showDialog" title="基本信息" width="650px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" style="flex: 1;">
        <el-form-item label="商品名称" prop="GoodId">
          <el-select v-model="form.GoodId" filterable placeholder="请选择商品名称" style="width: 100%">
            <el-option v-for="item in productOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="Batch">
          <el-input v-model="form.Batch" disabled placeholder="请输入生产批次" maxlength="30" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="QGPeriod">
          <el-input v-model="form.QGPeriod" placeholder="请输入保质期" maxlength="5" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="PLNumber">
          <el-input v-model="form.PLNumber" placeholder="请输入生产许可证号" maxlength="30" />
        </el-form-item>
        <el-form-item label="生产企业" prop="Manufacturer">
          <el-input v-model="form.Manufacturer" placeholder="请输入生产企业" maxlength="30" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <el-upload :key="uploadKey" class="avatar-uploader beautify-uploader" action="#" :show-file-list="false"
            :on-change="handleUpload" :before-upload="beforeUpload" :limit="1" :auto-upload="false">
            <div v-if="form.CoverImg" class="cover-wrapper">
              <img :src="form.CoverImg" class="avatar beautify-avatar" />
              <transition name="fade">
                <span class="delete-btn beautify-delete" v-show="hovering" @click.stop="removeCover">×</span>
              </transition>
            </div>
            <div v-else class="beautify-upload-btn" @mouseenter="hovering = true" @mouseleave="hovering = false">
              <el-icon>
                <Plus />
              </el-icon>
              <div class="upload-text">上传封面图</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
        <el-dialog v-model="showUpdDialog" title="基本信息编辑" width="650px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" style="flex: 1;">
        <el-form-item label="商品名称" prop="GoodId">
          <el-select v-model="form.GoodId" filterable placeholder="请选择商品名称" style="width: 100%">
            <el-option v-for="item in productOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="Batch">
          <el-input v-model="form.Batch" readonly maxlength="6" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="QGPeriod">
          <el-input v-model="form.QGPeriod" placeholder="请输入保质期" maxlength="5" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="PLNumber">
          <el-input v-model="form.PLNumber" placeholder="请输入生产许可证号" maxlength="30" />
        </el-form-item>
        <el-form-item label="生产企业" prop="Manufacturer">
          <el-input v-model="form.Manufacturer" placeholder="请输入生产企业" maxlength="30" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <el-upload :key="uploadKey" class="avatar-uploader beautify-uploader" action="#" :show-file-list="false"
            :on-change="handleUpload" :before-upload="beforeUpload" :limit="1" :auto-upload="false">
            <div v-if="form.CoverImg" class="cover-wrapper">
              <img :src="form.CoverImg" class="avatar beautify-avatar" />
              <transition name="fade">
                <span class="delete-btn beautify-delete" v-show="hovering" @click.stop="removeCover">×</span>
              </transition>
            </div>
            <div v-else class="beautify-upload-btn" @mouseenter="hovering = true" @mouseleave="hovering = false">
              <el-icon>
                <Plus />
              </el-icon>
              <div class="upload-text">上传封面图</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, ShoppingBag } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'
import axios from 'axios'
import moment from 'moment'

onMounted(() => {
  ShowBasic()
  ShowGood()
})
const productOptions = ref([])
//显示商品信息321
//显示商品信息123
const ShowGood = () => {
  axios.get("http://localhost:5266/api/BasicTraceability/GetGood").then(res => {
    productOptions.value = res.data.Data.map(item => ({
      value: item.Id,
      label: item.GoodName
    }))
  })
}
//显示溯源基础信息
const tableData = ref([])
const Total = ref({
  PageIndex: 1,
  PageSize: 15,
  TotalPage: 1,
  TotalCount: 1
})
const ShowBasic = () => {
  axios.get("http://localhost:5266/api/BasicTraceability/GetBasicTraceability", {
    params: {
      PageIndex: Total.value.PageIndex,
      PageSize: Total.value.PageSize
    }
  }).then(res => {
    tableData.value = res.data.PageDatas
    Total.value.TotalCount = res.data.TotalCount
    Total.value.TotalPage = res.data.TotalPage
  })
}

const showDialog = ref(false)
const formRef = ref(null)
const form = reactive({
  GoodId: '',
  Batch: '',
  QGPeriod: '',
  PLNumber: '',
  Manufacturer: '',
  Information: 0,
  CoverImg: ''
})
//表单校验
const rules = {
  GoodId: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  Batch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { max: 30, message: '最多30位字符', trigger: 'blur' }
  ],
  QGPeriod: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '只允许输入最多5位数字', trigger: 'blur' }
  ],
  PLNumber: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { max: 30, message: '最多30位字符', trigger: 'blur' }
  ],
  Manufacturer: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { max: 30, message: '最多30位字符', trigger: 'blur' }
  ],
  CoverImg: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ]
}
const handleAdd = () => {
  showDialog.value = true
  // 清空表单
  Object.assign(form, {
    GoodId: '',
    // 新增时自动生成6位数字批次号
    Batch: generateBatchNumber(),
    QGPeriod: '',
    PLNumber: '',
    Manufacturer: '',
    Information: '0',
    CoverImg: ''
  })

}
const selectedRows = ref([])

// 处理表格选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理删除按钮点击
const handleDelete = () => {

  // 获取所有选中行的Id
  const selectedIds = selectedRows.value.map(row => row.Id)
  
  // 删除逻辑
  if (selectedIds.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  const id = ref()
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedIds.length} 条溯源商品?`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      axios.get("http://localhost:5266/api/BasicTraceability/DelBasicTraceability", { params: { Id: selectedIds.toString() } }).then(res => {
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message)
          ShowBasic()
        } 
        else {
          ElMessage.warning(res.data.Message)
        }
      })
    
  })
}

const handleDetail = (row) => {
  // 详情逻辑
  router.push({ path: "/ShowXQ" ,query:{Batch:row}})
}
// 修改逻辑
const showUpdDialog = ref(false);
const handleEdit = (row) => {
  showUpdDialog.value = true
  Object.assign(form, row)
  // 编辑时不自动生成批次号，保留原有
  uploadKey.value++
}
const handleUpd = () =>{
  axios.post("http://localhost:5266/api/BasicTraceability/UpdBasicTraceability",form).then(res=>{
    if (res.data.Code == 200) {
      ElMessage.success(res.data.Message)
      ShowBasic()
      showUpdDialog.value = false
    }
    else {
      ElMessage.warning(res.data.Message)
    }
  })
}

const handleExport = (row) => {
  // 导出溯源码逻辑
}

const handleDeleteRow = (row) => {

  ElMessageBox.confirm(
    '确认删除该溯源商品?',
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.get("http://localhost:5266/api/BasicTraceability/DelBasicTraceability", { params: { Id: row } }).then(res => {
      if (res.data.Code == 200) {
        ElMessage.success(res.data.Message)
        ShowBasic()
      }
      else {
        ElMessage.warning(res.data.Message)
      }
    })
  })
}
//添加溯源基本信息
const handleSave = () => {
  axios.post("http://localhost:5266/api/BasicTraceability/CreateBasicTraceability", form).then(res => {
    if (res.data.Code == 200) {
      ElMessage.success(res.data.Message)
      ShowBasic()
      showDialog.value = false
    }
    else {
      ElMessage.warning(res.data.Message)
    }
  })
}
//文件上传
const handleUpload = (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  
  axios.post('http://localhost:5266/api/FileUpload/UploadFile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (typeof res.data === 'string' && res.data.startsWith('http')) {
      form.CoverImg = res.data.split('?')[0]
      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error('文件上传失败')
    }
  })
}

const uploadKey = ref(0)
const hovering = ref(false)

const removeCover = () => {
  form.CoverImg = ''
  uploadKey.value++
}

const beforeUpload = (file) => {
  // 可加类型/大小校验
  return true
}

// 修改1：添加自动生成6位数字批次号的函数
function generateBatchNumber() {
  const date = new Date();
  const yymmdd = date.getFullYear().toString().slice(2, 4) +
    (date.getMonth() + 1).toString().padStart(2, '0') +
    date.getDate().toString().padStart(2, '0');
  const rand = Math.floor(Math.random() * 90 + 10); // 2位随机数
  return yymmdd + rand; // 共6位
}

const changePageSize = (size) => {
  if (Total.PageSize !== size) {
    Total.PageSize = size
    Total.PageIndex = 1
    ShowBasic()
  }
}
</script>

<style scoped>
.traceability-container {
  padding: 32px 24px 24px 24px;
  background: #f8f9fb;
  border-radius: 16px;
  min-height: 100vh;
}

.table-scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.08);
}

.footer-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.btn-group {
  display: flex;
  gap: 16px;
  margin-bottom: 10px;
}

.btn-group .el-button {
  box-shadow: 0 2px 8px 0 rgba(64, 158, 255, 0.08);
  font-size: 15px;
  transition: box-shadow 0.2s;
}

.btn-group .el-button:hover {
  box-shadow: 0 4px 16px 0 rgba(64, 158, 255, 0.16);
}

.beauty-table {
  border-radius: 12px;
  box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.08);
  overflow: hidden;
  background: #fff;
}

.beauty-table .el-table__header th {
  background: #f2f3f5;
  color: #222;
  font-weight: bold;
  font-size: 16px;
  border-bottom: 2px solid #ebeef5;
}

.beauty-table .el-table__row:hover>td {
  background: #f5f7fa !important;
  transition: background 0.2s;
}

.action-link {
  margin: 0 10px;
  font-weight: 500;
  transition: text-decoration 0.2s, background 0.2s;
  padding: 2px 6px;
  border-radius: 4px;
}

.action-link:hover {
  text-decoration: underline;
  background: #f2f6fc;
}

.beauty-pagination {
  margin-top: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 滚动条美化 */
.beauty-table ::-webkit-scrollbar {
  height: 8px;
  background: #f2f3f5;
  border-radius: 4px;
}

.beauty-table ::-webkit-scrollbar-thumb {
  background: #d4d7de;
  border-radius: 4px;
}

.avatar-uploader.beautify-uploader {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.cover-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.10);
  border: 2px solid #e4e7ed;
  background: #fafbfc;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.cover-wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 6px 24px rgba(64, 158, 255, 0.15);
}

.avatar.beautify-avatar {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 12px;
  box-shadow: none;
}

.beautify-delete {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 50%;
  width: 22px;
  height: 22px;
  text-align: center;
  line-height: 22px;
  font-size: 16px;
  cursor: pointer;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
  opacity: 0.85;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s, opacity 0.2s;
}

.cover-wrapper:hover .beautify-delete {
  opacity: 1;
  background: #f56c6c;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.beautify-upload-btn {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #bfbfbf;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s;
}

.beautify-upload-btn:hover {
  border-color: #409eff;
  background: #f4faff;
  color: #409eff;
}

.beautify-upload-btn .el-icon {
  font-size: 32px;
  margin-bottom: 6px;
}

.upload-text {
  font-size: 13px;
  color: #999;
}

.page-size-group {
  display: inline-block;
  vertical-align: middle;
}
</style>